package favorites

import (
	"file_explorer/common/log"
	"file_explorer/model"
	"file_explorer/service/eventbus"
	"file_explorer/view/components/side_panel/dir_tree"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"
)

type FavoritesList struct {
	*packed_widgets.Tree

	gCtx *store.GlobalContext
}

func (favoritesList *FavoritesList) refreshData() {
	gConf := favoritesList.gCtx.GetGlobalConf()
	favoritesDirs := make([]*packed_widgets.TreeNode, len(gConf.Favorites))
	for i, favorites := range gConf.Favorites {
		favoritesDirs[i] = &packed_widgets.TreeNode{
			NodeId: favorites.Path,
			Label:  favorites.Name,
			Depth:  0,
		}
	}
	favoritesList.Tree.SetData(&packed_widgets.TreeNode{
		NodeId:   "",
		Label:    "\\",
		Children: favoritesDirs,
	})
	favoritesList.Tree.Refresh()
}

func NewFavorites(gCtx *store.GlobalContext) *FavoritesList {
	favoritesList := &FavoritesList{
		gCtx: gCtx,
		Tree: packed_widgets.NewTree(nil),
	}

	favoritesList.refreshData()

	dir_tree.SetDirTreeEvents(gCtx, favoritesList.Tree)

	gCtx.RegisterConsumer(eventbus.EventKeyGlobalConfUpdate, func(event *model.Event) {
		if event.Msg["conf_key"] != model.ConfKeyFavorites {
			return
		}
		log.Info("收藏夹更新，刷新侧边栏")
		favoritesList.refreshData()
	})

	return favoritesList
}
